#import "TDDropView.h"
#import "TDObject.h"

@implementation TDDropView

- (id) initWithFrame:(NSRect)frameRect
{
	self = [super initWithFrame: frameRect];
	
	if (self) 
	{

		NSBundle *bundle = [NSBundle mainBundle];

		_fullTrashImage =		[[NSImage alloc] initWithContentsOfFile: 
									[bundle pathForResource:@"FullTrashIcon"	ofType: @"png"]];
							
		_appDraggedImage =		[[NSImage alloc] initWithContentsOfFile: 
									[bundle pathForResource:@"AppDragged2"		ofType: @"png"]];
							
		_trashImage =			[[NSImage alloc] initWithContentsOfFile: 
									[bundle pathForResource:@"TrashIcon"		ofType: @"png"]];
							
		_statusBorderImage =	[[NSImage alloc] initWithContentsOfFile: 
									[bundle pathForResource:@"StatusBorder"		ofType: @"png"]];
		
		[bundle release];
	}
	
	return self;
}

- (void) dealloc
{
	[_fullTrashImage release];
	[_appDraggedImage release];
	[_trashImage release];
	[_statusBorderImage release];
	
	[super dealloc];
}

- (void) drawRect:(NSRect)rect
{
	[super drawRect: rect];
}

#pragma mark Drag and drop
- (NSDragOperation) draggingEntered:(id <NSDraggingInfo>)sender 
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSPasteboard *pboard;
    NSDragOperation sourceDragMask;
	NSString *path;
	
    
    sourceDragMask = [sender draggingSourceOperationMask];
    pboard = [sender draggingPasteboard];
	
	//	This could use some refactoring.  
    if ([[pboard types] containsObject:NSFilenamesPboardType])
	{
		KHFileUtil *fileUtil = [[KHFileUtil alloc] init];
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
		NSEnumerator *fileEnum = [files objectEnumerator];
		

		
		//	Return as soon as ANY of the objects passed are valid.
		while (path = [fileEnum nextObject])
		{
			if ([fileUtil pathContainsApp: path])
			{
				[fileUtil release];
				
				[imageView_dropImage setImage: _fullTrashImage];
				[imageView_dropImage display];
				[imageView_dropBackground setImage: _appDraggedImage]; // Not working, why?
	
				return NSDragOperationGeneric;
			}
		}
		
		[fileUtil release];
    }
	
	//	No .app found anywhere :(
	[pool release];
	
	return NSDragOperationNone;
}

- (BOOL) performDragOperation:(id <NSDraggingInfo>)sender 
{
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSPasteboard *pboard;
    NSDragOperation sourceDragMask;	

    
    sourceDragMask = [sender draggingSourceOperationMask];
    pboard = [sender draggingPasteboard];
	
    if ( [[pboard types] containsObject:NSFilenamesPboardType] ) 
	{
        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
		[[TDObject sharedAppScrapperInstance] prepareStuff:files];
		[pool release];
		return YES;
	}
	[pool release];
	return NO;


}

- (void) draggingExited:(id <NSDraggingInfo>)sender
{
    [imageView_dropImage setImage: _trashImage];
    [imageView_dropBackground setImage: _statusBorderImage];
}

@end
